#include "include/packet.h"

// This is reverse engineered code and is not intended to run (or even compile at this point)
// We need code reviews on these functions, as much as possible

// Param 1 is some sort of state tracking buffer
// Param 2 points to the whole packet, including the header
// Param 3 is the buffer size of 'data'
// Param 4 points to the start of data in the packet (param 2 + 0x0C)
// Packet header is 0x0C bytes in size
void sub_6DBCE0(struct RomDecryptionState *state, struct RomPacketHeader *packet, int size, char* data)
{
    // Reserve 16 Bytes    
    uint32_t  local_0;
    uint32_t  local_8;
    uint32_t  local_C;
    uint32_t  local_key;    // Key?

    // Most packets take this branch (about 1400 out of 1900 logged packets did)
    if (packet->keybytes[0] == 2)
    {
        if (++state->counterA >= 10)
            state->counterA = 0;

        // I think the key offset can be calculated by doing packet % 0x0A instead of looking at the state->counterA variable
        local_key = state->keys[state->counterA - 1];

        // Actual decryption loop, super hardcore encryption code guys!
        if (size != 0)
            for(int i = 0; i < size; i++)
            {
                data[i] += key;
                data[i] ^= key;
            }

        // 0x006DBD52 (Client.exe + 0x002DBD52)
        // Here the assembly does something weird
        // It uses the 'state' pointer to temporarily save a byte, and never uses direct access from arg1 after that
        // It does still have 'state' in a register
        // the following call never changes the packet buffer and I suspect the compiler does this weird stuff
        // because the programmers didnt mark the buffer as 'const'
        // Please review so we ran remove the 'weird' variable
        char weird = packet->keybytes[1];
        char temp = sub_6D7AA0(packet, size + 0x0C, local_key, 0);
        temp -= packet->keybytes[2];
        temp -= weird;

        if (temp == weird)
            return sub_6D8BE0(state, size, data, packet); // TODO: Almost all packets end here, this is priority to reverse

        // The following function call is taken from the vtable of the object
        // I placed a breakpoint on this call but it never got hit,  probably a rare case
        // the this pointer seems to be the same always, but might have a different vtable in some cases
        // I've taken the function out of the vtable from the other calls to this function (that dont hit this branch)
        // This may be incorrect
        sub_6DD760(state->not_sure);
    }
    else
    {
        
    }
}


uint8_t sub_6D7AA0(const uint8_t *buffer, uint32_t size, uint8_t a3, uint8_t a4)
{
        for(int i = 0; i < size; i++)
            a4 += buffer[i];
        
        return a3 + a4;
}
